using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using JGSY.CMS.LowCode.Platform.Domain.Entities;
using JGSY.CMS.LowCode.Platform.Domain.Interfaces;
using System.Linq.Expressions;
using JGSY.CMS.LowCode.Platform.Infrastructure.CmsDbContext;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Repositories
{
    /// <summary>
    /// 团队成员仓储实现
    /// </summary>
    public class TeamMemberRepository : Repository<TeamMember>, ITeamMemberRepository
    {
        public TeamMemberRepository(LowCodeDbContext context) : base(context)
        {
        }

        /// <summary>
        /// 根据团队ID获取成员列表
        /// </summary>
        public async Task<List<TeamMember>> GetByTeamIdAsync(long teamId)
        {
            return await _context.TeamMembers
                .Where(x => x.TeamId == teamId)
                .Include(x => x.User)
                .OrderBy(x => x.JoinedAt)
                .ToListAsync();
        }

        /// <summary>
        /// 根据用户ID获取团队成员列表
        /// </summary>
        public async Task<List<TeamMember>> GetByUserIdAsync(long userId)
        {
            return await _context.TeamMembers
                .Where(x => x.UserId == userId)
                .Include(x => x.Team)
                .OrderBy(x => x.JoinedAt)
                .ToListAsync();
        }

        /// <summary>
        /// 检查用户是否为团队成员
        /// </summary>
        public async Task<bool> IsMemberAsync(long teamId, long userId)
        {
            return await _context.TeamMembers
                .AnyAsync(x => x.TeamId == teamId && x.UserId == userId);
        }

        /// <summary>
        /// 获取团队成员角色
        /// </summary>
        public async Task<string?> GetMemberRoleAsync(long teamId, long userId)
        {
            var member = await _context.TeamMembers
                .FirstOrDefaultAsync(x => x.TeamId == teamId && x.UserId == userId);
            
            return member?.Role;
        }

        /// <summary>
        /// 获取团队管理员列表
        /// </summary>
        public async Task<List<TeamMember>> GetTeamAdminsAsync(long teamId)
        {
            return await _context.TeamMembers
                .Where(x => x.TeamId == teamId && (x.Role == "Admin" || x.Role == "Leader"))
                .Include(x => x.User)
                .OrderBy(x => x.JoinedAt)
                .ToListAsync();
        }
    }
}
